package es.udc.pfc.davidparedes.test.experiments;

import java.util.Calendar;

import org.hibernate.Transaction;

import es.udc.pfc.davidparedes.model.receptionist.Receptionist;
import es.udc.pfc.davidparedes.model.store.Store;
import es.udc.pfc.davidparedes.model.store.StoreDao;
import es.udc.pfc.davidparedes.model.store.StoreDaoHibernate;
import es.udc.pfc.davidparedes.model.userprofile.UserProfile;
import es.udc.pfc.davidparedes.model.userprofile.UserProfileDao;
import es.udc.pfc.davidparedes.model.userprofile.UserProfileDaoHibernate;
import es.udc.pfc.davidparedes.model.userservice.util.PasswordEncrypter;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;

public class DaoExperiments {

	public static void main(String[] args) {

		UserProfileDaoHibernate userProfileDaoHibernate = new UserProfileDaoHibernate();
		userProfileDaoHibernate.setSessionFactory(HibernateUtil
				.getSessionFactory());
		UserProfileDao userProfileDao = userProfileDaoHibernate;
		
		StoreDaoHibernate storeDaoHibernate = new StoreDaoHibernate();
		storeDaoHibernate.setSessionFactory(HibernateUtil.getSessionFactory());
		StoreDao storeDao = storeDaoHibernate;

		Transaction tx = HibernateUtil.getSessionFactory().getCurrentSession()
				.beginTransaction();
		try {
			// Register store
			Store store = new Store("daoStore", "direccion de la store, Galicia");
			storeDao.save(store);
			Long storeId = store.getStoreId();
			System.out.println("Store con storeId '" + storeId
					+ "' ha sido creada");
			System.out.println(store);

			// Register user.
			Calendar contractTermination = Calendar.getInstance();
			UserProfile userProfile = new Receptionist("daoUser",
					PasswordEncrypter.crypt("userPassword"), "name",
					"lastName", "user@udc.es", "12345678A", store, contractTermination);
			userProfileDao.save(userProfile);
			Long userId = userProfile.getUserProfileId();
			System.out.println("User with userId '" + userId
					+ "' has been created");
			System.out.println(userProfile);

			// Find user.
			userProfile = userProfileDao.find(userId);
			System.out.println("User with userId '" + userId
					+ "' has been retrieved");
			System.out.println(userProfile);
			
			// ... proceed in the same way for other entities / methods / use cases

			tx.commit();

		} catch (RuntimeException e) {
			e.printStackTrace();
			tx.rollback();
		} catch (InstanceNotFoundException e) {
			e.printStackTrace();
			tx.commit();
		} finally {
			HibernateUtil.getSessionFactory().getCurrentSession().close();
		}

		HibernateUtil.shutdown();

	}

}
